<template>
  <Dialog v-model="dialogVisible" title="聚类结果" width="500" align-center>
    <div class="task-name"><span>任务名称：</span>{{ taskName }}</div>
    <el-table :data="list" row-key="id" border>
      <el-table-column prop="result" label="结果名称" align="center" />
      <el-table-column prop="similarity" label="最低相似度" align="center" />
      <el-table-column label="操作" width="130" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="editResult(scope.row.id, scope.row.threshold)">
            查看
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button @click="closeDialog">关 闭</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { getClusterTaskResult, deleteClusterTaskResult } from '@/api/develop/clusterTask'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const router = useRouter()
const formLoading = ref(false) // 表单的加载中：提交的按钮禁用
const dialogVisible = ref(false) // 弹窗的是否展示
const taskName = ref('')

const list = ref([]) // 列表的数据

let taskId

/** 打开弹窗 */
const open = async (id: number, name: string) => {
  dialogVisible.value = true
  taskName.value = name

  taskId = id

  getList()
}

async function getList() {
  if (!taskId) {
    return
  }
  formLoading.value = true
  try {
    const res = await getClusterTaskResult(taskId)
    list.value = res.map((item) => {
      return {
        id: item.id,
        result: item.name,
        similarity: (Number(item.threshold) * 100).toFixed(0) + '%',
        threshold: item.threshold
      }
    })
  } finally {
    formLoading.value = false
  }
}

async function handleDelete(id) {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteClusterTaskResult(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

function editResult(id, threshold) {
  router.push({
    name: 'EditClustering',
    params: { taskId: taskId, resultId: id, threshold }
  })
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

function closeDialog() {
  dialogVisible.value = false
}

function resetForm() {
  taskName.value = ''
  list.value = []
}

watch(dialogVisible, (show) => {
  !show && resetForm()
})
</script>
<style lang="scss" scoped>
.task-name {
  margin: 0 0 20px 0;
  font-size: 16px;
  color: #333;
  span {
    color: #909399;
  }
}
</style>
